package com.zyf.chapter01.practice.v2;

import com.zyf.chapter01.principle.practice.MetricsStorage;
import com.zyf.chapter01.principle.practice.RequestInfo;
import com.zyf.chapter01.principle.practice.RequestStat;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 组装类
 * 第四个逻辑：组装类并定时触发执行逻辑
 * @author yifeng
 */
public class ConsoleReporter {
    private MetricsStorage metricsStorage;
    private Aggregator aggregator;
    private StatViewer viewer;
    private ScheduledExecutorService executor;

    public ConsoleReporter(MetricsStorage metricsStorage, Aggregator aggregator, StatViewer viewer) {
        this.metricsStorage = metricsStorage;
        this.aggregator = aggregator;
        this.viewer = viewer;
        executor = Executors.newSingleThreadScheduledExecutor();
    }

    public void startRepeatedReport(long periodInSeconds, long durationInSeconds) {
        executor.scheduleAtFixedRate((Runnable) () -> {
            // 第一个代码逻辑：根据给定的时间区间，从数据库中拉取数据;
            // 该代码逻辑不需要重构
            long durationInMillis = durationInSeconds * 1000;
            long endTimeInMillis = System.currentTimeMillis();
            long startTimeInMillis = endTimeInMillis - durationInMillis;
            Map<String, List<RequestInfo>> requestInfos =
                    metricsStorage.getRequestInfos(startTimeInMillis, endTimeInMillis);
            HashMap<String, RequestStat> stats = new HashMap<>();
            // 重构点：数据统计任务交给聚合器
            aggregator.aggregate(requestInfos, durationInMillis);
            // 重构点：输出的任务交给统计视图
            viewer.output(stats, startTimeInMillis, endTimeInMillis);

        }, 0, periodInSeconds, TimeUnit.SECONDS);
    }
}
